package com.company.project.robot.service.impl;

import com.company.project.common.exception.BusinessException;
import com.company.project.common.utils.ExcelUtils;
import com.company.project.robot.entity.DialogueEntity;
import com.company.project.robot.entity.JokesEntity;
import com.company.project.robot.mapper.DialogueMapper;
import com.company.project.robot.service.DialogueService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@Service("dialogueService")
public class DialogueServiceImpl extends ServiceImpl<DialogueMapper, DialogueEntity> implements DialogueService {


    /**
     * 导出模板
     * @param request
     * @param response
     * @throws IOException
     */
    @Override
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String[] excelHeader = { "关键字","答案","是否完全匹配" };
        String[] columnNames = { "problem","answer","isMatch" };
        int[] ds_format = { 2, 2, 2 };
        String[] sumColumns = { "", "", ""};
        ExcelUtils.export("对话导入模板.xlsx", null, excelHeader, columnNames, sumColumns, ds_format, null,
                null, request, response);
    }


    /**
     * 导入
     *
     * @param file
     * @return
     * @throws Exception
     */
    @Override
    public String excelImport(MultipartFile file) throws Exception {
        //获取Excel格式
        int type = readExcel(file.getOriginalFilename());
        Workbook wb = null;
        //获取第一个工作表的数据（其他工作表数据不操作）
        Sheet sheet = null;
        //xls格式
        if (type == 1) {
            wb = new HSSFWorkbook(file.getInputStream());
        } else if (type == 2) {//xlsx格式
            wb = new XSSFWorkbook(file.getInputStream());
        } else {
            throw new BusinessException("请导入正确文件类型");
        }
        if (wb != null && wb.getNumberOfSheets() > 0) {
            for (int i = 0; i < wb.getNumberOfSheets(); i++) {
                if (wb.getSheetAt(i).getPhysicalNumberOfRows() > 0) {
                    sheet = wb.getSheetAt(i);
                    break;
                }
            }
        } else {
            throw new BusinessException("导入失败");
        }
        //判断第一行的第1、2列的名称，不符合则提示模板文件不对
        Row r = sheet.getRow(0);
        if (!r.getCell(0).getStringCellValue().equals("关键字")
                || !r.getCell(1).getStringCellValue().equals("答案") ||
                !r.getCell(2).getStringCellValue().equals("是否完全匹配")) {
            throw new BusinessException("请选择正确的模板文件再导入");
        }
        List<DialogueEntity> list = new ArrayList<>();
        for (int i = 1, length = sheet.getLastRowNum(); i <= length; i++) {
            Row row = sheet.getRow(i);
            //判断第1，2列是否有空值
            if (
                    row.getCell(0) == null|| row.getCell(1) == null|| row.getCell(2) == null
            ) {
                throw new BusinessException("部分数据导入成功<br>,已导入到第" + i + "行,在【" + (i + 1) + "】行有空数据");
            }
            DialogueEntity entity = new DialogueEntity();
            entity.setProblem(row.getCell(0).getStringCellValue());
            entity.setAnswer(row.getCell(1).getStringCellValue());
            if(null != row.getCell(2)){
                if(row.getCell(2).getStringCellValue().equals("是")){
                    entity.setIsMatch(1);
                }else{
                    entity.setIsMatch(2);
                }
            }
            entity.setDeleted(1);
            list.add(entity);
        }
        this.saveBatch(list);
        return "导入成功";
    }

    /**
     * 读取excel格式
     *
     * @param fileName
     * @return
     * @throws Exception
     */
    private int readExcel(String fileName) {
        String extString = fileName.substring(fileName.lastIndexOf("."));
        try {
            if (".xls".equals(extString)) {
                return 1;
            } else if (".xlsx".equals(extString)) {
                return 2;
            } else {
                return 0;
            }
        } catch (Exception e) {
            log.error("读取Excel文件异常" + e);
            throw new BusinessException("读取Excel文件异常");
        }
    }


}